<template>
  <!-- 主体区域 -->
  <section id="app">
    <!-- 输入框 -->
    <TodoHeader @add="addTodoName"></TodoHeader>

    <!-- 列表区域 -->
    <TodoMain :list="list" @del="del"></TodoMain>
    
    <!-- 统计和清空 -->
    <TodoFooter :list="list" @clear="clear"></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  data () {
    return {
      list:JSON.parse(localStorage.getItem('list'))||[
        { id: 1, name: '打篮球' },
        { id: 2, name: '看电影' },
        { id: 3, name: '逛街' },
      ]
    }
  },
  components:{
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  methods:{
    
    addTodoName(name){
      if(!name){
        alert('请输入任务')
        return
      }
      this.list.unshift({
        id:+new Date(),
        name
      })
    },
    del(id){
      // console.log(id);
      this.list = this.list.filter((item)=>item.id!==id)
    },
    clear(){
      this.list=[]
    }
  },
  watch:{
    list:{
      deep:true,
      handler(newObj){
        
        console.log(newObj);
        if(newObj.length == 0){
          localStorage.removeItem('list')
        }else {
          localStorage.setItem('list',JSON.stringify(newObj))
        }
        
      }
    }
  }
}
</script>

<style>

</style>
